package com.itheima.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.dao.DishDao;
import com.itheima.domain.*;
import com.itheima.dto.DishDto;
import com.itheima.service.CategoryService;
import com.itheima.service.DishFlavorService;
import com.itheima.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 *   新增菜品，同时保存对应的口味数据
 */

@Service
public class DishServiceImpl extends ServiceImpl<DishDao, Dish> implements DishService {

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishService dishService;

    //菜品管理菜品新增
    @Override
    public void saveWithFlavor(DishDto dishDto) {
        save(dishDto);
        //取出所有口味
        List<DishFlavor> flavors = dishDto.getFlavors();
        //为每个口味添加的菜品id
        Long id = dishDto.getId();
        //循环设置到口味对象中
        flavors.stream().forEach(c->c.setDishId(id));
        //保存到数据库中
        dishFlavorService.saveBatch(flavors);

    }
    //菜品管理分页查询
    @Autowired
    private CategoryService categoryService;

    @Override
    public Page<DishDto> findByPage(Integer page, Integer pageSize, String name) {
        //构建分页条件对象
        /*Page<Dish> iPage = new Page<>(size,pageSize);
        LambdaQueryWrapper<Dish> wapper = new LambdaQueryWrapper<>();
        //添加查询条件
        if(null!=name){
            wapper.like(Dish::getName,name);
        }
        wapper.orderByDesc(Dish::getCreateTime);
        //dishFlavorService.page(iPage, wapper);
        Page<Dish> page = this.page(iPage,wapper);
        //把原有的Dish对象封装到DishDto对象中
        //集合
        List<Dish> dishes = page.getRecords();

        //ArrayList<DishDto> dishDtos = new ArrayList<>();
        //深克隆
        List<DishDto> dishDtos = JSON.parseArray(JSON.toJSONString(dishes), DishDto.class);
        //遍历
        for (DishDto dishDto : dishDtos) {
            Long categoryId = dishDto.getCategoryId();
            Category category = categoryService.getById(categoryId);
            dishDto.setCategoryName(category.getName());
        }
            Page<DishDto> dtoPage = new Page<>();
            dtoPage.setRecords(dishDtos);
            dtoPage.setTotal(page.getTotal());
        return dtoPage;
    }*/

        //1.构建分页条件对象
        Page<Dish> pageInfo = new Page(page,pageSize);
        LambdaQueryWrapper<Dish> wapper =new LambdaQueryWrapper<>();
        if(null!=name && name != ""){
            //添加模糊查询
            wapper.like(Dish::getName,name);
        }
        //因为新的菜品应该放在前面，所以需要添加一个排序规则
        //Desc 从大到小
        wapper.orderByDesc(Dish::getUpdateTime);
        //分页查询
        Page<Dish> page1 = this.page(pageInfo, wapper);
        //把原有的Dish对象重新封装程一个DishDto 对象
        List<Dish> dishes = page1.getRecords();
        //把List<Dish> 中的所有数据复制到 List<DishDto>
        //BeanUtils.copyProperties(dishes,dishDtos);
        List<DishDto> dishDtos = JSON.parseArray(JSON.toJSONString(dishes), DishDto.class);

        for (DishDto dishDto : dishDtos) {
            Long categoryId = dishDto.getCategoryId();//获得分类id
            //根据分类id 查询分类名称
            Category category = categoryService.getById(categoryId);
            //把分类的名字设置给dto对象
            dishDto.setCategoryName(category.getName());
        }
        Page<DishDto> dtoPage = new Page<>();
        dtoPage.setRecords(dishDtos);
        dtoPage.setTotal(page1.getTotal());

        return dtoPage;
    }

    //菜品管理单个删除
    /*@Override
    public R delectById(Long id) {
        LambdaQueryWrapper<Dish> wapper = new LambdaQueryWrapper<>();
        wapper.eq(Dish::getId,id);
        Dish one = dishService.getOne(wapper);
        if(one == null){
            return R.error("删除失败");
        }
       //dishService.removeById(id);
        return R.success("删除成功");
    }*/

    //菜品管理修改回显数据
    @Override
    public DishDto dishDtoById(Long id) {
        Dish dish = this.getById(id);
        DishDto dishDto = new DishDto();
        BeanUtils.copyProperties(dish,dishDto);
        LambdaQueryWrapper<DishFlavor> wapper = new LambdaQueryWrapper<>();
        wapper.eq(DishFlavor::getDishId,dish.getId());
        List<DishFlavor> flavors = dishFlavorService.list(wapper);
        dishDto.setFlavors(flavors);
        return dishDto;
    }

    //菜品管理修改数据
    @Override
    @Transactional
    public void updateDishDto(DishDto dishDto) {
        this.updateById(dishDto);
        List<DishFlavor> flavors = dishDto.getFlavors();

        //为每个口味设置菜品id
        flavors = flavors.stream().map(c->{
            c.setDishId(dishDto.getId());
            return c;
        }).collect(Collectors.toList());
        //增删改 用LambdaUpdateWrapper
        LambdaUpdateWrapper<DishFlavor> wapper = new LambdaUpdateWrapper<>();
        wapper.eq(DishFlavor::getDishId,dishDto.getId());
        //先删除
        dishFlavorService.remove(wapper);
        //再添加
        dishFlavorService.saveOrUpdateBatch(flavors);
    }

    //根据条件查询对应的菜品数据
    @Override
    public List<DishDto> findDishByCategoryID(Long categoryId) {
        LambdaQueryWrapper<Dish> wapper = new LambdaQueryWrapper<>();
        wapper.eq(Dish::getCategoryId,categoryId);
        List<Dish> list = dishService.list(wapper);

        String string = JSON.toJSONString(list);
        List<DishDto> dishDtos = JSON.parseArray(string, DishDto.class);

        for (DishDto dishDto : dishDtos) {
            //封装口味信息
            LambdaQueryWrapper<DishFlavor> flavorwapper = new LambdaQueryWrapper<>();
            flavorwapper.eq(DishFlavor::getDishId,dishDto.getId());
            List<DishFlavor> flavors = dishFlavorService.list(flavorwapper);
            if(flavors.size()>0){
                dishDto.setFlavors(flavors);
            }
            //封装分类名称
            Category category = categoryService.getById(dishDto.getCategoryId());
            if(category!=null){
                dishDto.setCategoryName(category.getName());
            }
        }
        return dishDtos;
    }

    //菜品管理逻辑批量删除
    @Override
    public void deleteDishByIds(Long[] ids) {
        //数组强转为集合
        /*List<Long> list = JSON.parseArray(JSON.toJSONString(ids), Long.class);
        this.removeByIds(list);
        LambdaUpdateWrapper<DishFlavor> wapper = new LambdaUpdateWrapper<>();
        for (Long id : ids) {
            wapper.eq(DishFlavor::getDishId,id);
            dishFlavorService.remove(wapper);
        }
        return R.success("删除成功");
*/
        //数组强转为集合
        List<Dish> dishes = this.listByIds(Arrays.asList(ids));
        //循环修改所有套餐的is_deleted属性
        dishes.stream().map(c->{c.setIsDeleted(1);
            return c;
        }).collect(Collectors.toList());
        //修改
        this.updateBatchById(dishes);

        //修改菜品信息
        for (Dish dish : dishes) {
            LambdaUpdateWrapper<Dish> wapper = new LambdaUpdateWrapper<>();
            wapper.eq(Dish::getCategoryId,dish.getCategoryId());
            List<Dish> dishList = dishService.list(wapper);
            dishList.stream().map(c->{c.setIsDeleted(1);
                return c;
            }).collect(Collectors.toList());
            //更新套餐菜品数据
            dishService.updateBatchById(dishList);
        }
    }

    //菜品批量启用停售
    @Override
    public R updateByStatus(Long[] ids) {
        List<Long> list = JSON.parseArray(JSON.toJSONString(ids), Long.class);
        List<Dish> dishes = this.listByIds(list);
        for (Dish dish : dishes) {
            dish.setStatus(0);
            //修改
            this.updateById(dish);
        }
        return R.success("修改成功");
    }

    //菜品批量启用起售
    @Override
    public R updateByStatus1(Long[] ids) {
        List<Long> list = JSON.parseArray(JSON.toJSONString(ids), Long.class);
        List<Dish> dishes = this.listByIds(list);
        for (Dish dish : dishes) {
            dish.setStatus(1);
            this.updateById(dish);
        }
        return R.success("修改成功");
    }

}
